package com.junrry.communication

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import com.hoho.android.usbserial.driver.UsbSerialDriver
import com.hoho.android.usbserial.driver.UsbSerialPort
import com.hoho.android.usbserial.driver.UsbSerialProber
import com.junrry.communication.ktx.CustomGlobalScope
import com.junrry.communication.ktx.io
import com.junrry.communication.ktx.ui
import com.junrry.communication.databinding.ActivityPcBinding
import java.io.IOException

private const val TAG = "PcActivity_LJM"

class PcActivity : ComponentActivity() {

    private lateinit var binding: ActivityPcBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPcBinding.inflate(layoutInflater)
        setContentView(binding.root)

        registerUsbReceiver()

        initListener()

        initUsbManager()
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    private fun registerUsbReceiver() {
        val filter = IntentFilter(ACTION_USB_PERMISSION)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            registerReceiver(usbReceiver, filter, RECEIVER_EXPORTED)
        } else {
            registerReceiver(usbReceiver, filter)
        }
    }


    private fun initUsbManager() {
        //初始化Manager
        manager = getSystemService(USB_SERVICE) as UsbManager
        //获取驱动器
        val availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager)
        if (availableDrivers.isEmpty()) {
            return
        }

        val str = StringBuilder()
        val permissionIntent = PendingIntent.getBroadcast(
            this, 0,
            Intent(ACTION_USB_PERMISSION), 0
        )
        availableDrivers.forEach { d ->
            Log.d(TAG, "device = ${d.device.vendorId}  ${d.device.productId}")
            str.append("device = ${d.device.vendorId}  ${d.device.productId}\n")
            if (d.device.vendorId == 6790 && d.device.productId == 29987) {//指定设备连接
                driver = d
                usbDevice = driver.device
                //获取授权
                manager.requestPermission(usbDevice, permissionIntent)
            }
        }

        binding.tvDevice.text = str.toString()
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(usbReceiver)
        port?.close()
    }

    private fun initListener() {
        binding.btnSend.setOnClickListener {
            if (binding.etSend.text.isNullOrEmpty()) {
                Toast.makeText(this, "请输入发送内容", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (driver == null) {
                Toast.makeText(this, "请连接设备", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            CustomGlobalScope.io {
                sendMsg(binding.etSend.text.toString().trim())
            }
        }
    }

    private val ACTION_USB_PERMISSION = "android.permission.USB_PERMISSION"
    lateinit var usbDevice: UsbDevice
    lateinit var connection: UsbDeviceConnection
    lateinit var manager: UsbManager
    lateinit var driver: UsbSerialDriver
    lateinit var port: UsbSerialPort


    private val usbReceiver = object : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            if (ACTION_USB_PERMISSION == intent.action) {
                val device: UsbDevice? = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
                Toast.makeText(
                    this@PcActivity,
                    "permission" + intent.getBooleanExtra(
                        UsbManager.EXTRA_PERMISSION_GRANTED,
                        false
                    ),
                    Toast.LENGTH_SHORT
                ).show()
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    initConnectionSDK()
                } else {
                    Log.d(TAG, "permission denied for device $device")
                }
            }
        }
    }


    private fun initConnectionSDK() {
        connection = manager.openDevice(usbDevice)
        if (connection != null) {
            try {
                port = driver.ports[0]
                port.open(connection);
                //设置串口的波特率、数据位，停止位，校验位
                port.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
                val buffer = ByteArray(1024) // 数据缓存
                val str = StringBuilder()
                CustomGlobalScope.io {
                    // 循环读取数据
                    while (true) {
                        val numBytesRead = port.read(buffer, 1000)
                        if (numBytesRead > 0) {
                            // 处理接收到的数据
                            val receivedData = String(buffer, 0, numBytesRead)
                            str.append(receivedData + "\n")
                            CustomGlobalScope.ui {
                                binding.tvReceiver.text = str.toString()
                            }
                        }
                    }
                }
            } catch (e: Exception) {
                // Deal with error.
            } finally {

            }
        }
    }

    private fun sendMsg(msg: String) {
        try {
            port?.write(msg.toByteArray(), 1000)
        } catch (e: IOException) {
            // Deal with error.
        }
    }

}